package com.google.coffeeshop.gui.desktop.product;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Date;
import java.util.List;

import com.google.coffeeshop.business.CodeGenerationBusiness;
import com.google.coffeeshop.business.LoadingBusiness;
import com.google.coffeeshop.business.ManagerBusiness;
import com.google.coffeeshop.entity.EmployeeDTO;
import com.google.coffeeshop.entity.ProductDTO;
import com.google.coffeeshop.entity.ProductGroupDTO;
import com.google.coffeeshop.entity.ProductSellingPriceDTO;
import com.google.coffeeshop.gui.desktop.ObservingTextField;
import com.google.coffeeshop.gui.desktop.SwingFactory;
import com.google.coffeeshop.gui.desktop.selfcomponent.ImagePanel;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;

import vn.bang.utility.DateUtil;
import vn.bang.utility.FileUtil;
import vn.bang.utility.StringUtil;

public class ProductForm extends JFrame{	
	private static final long serialVersionUID = 1L;
	private JTextField txtCode;
	private JTextField txtName;
	private JComboBox cbbProductGroup;
	private ImagePanel pnlImage;

	private ProductPanel productPanel;
	JLabel lblProductTitle;
	private Long productID;
	private String image_filename = SwingFactory.NO_IMAGE_NAME;
	private ObservingTextField txtPrice;
	private List<ProductGroupDTO> listProductGroup;
	private ProductSellingPriceDTO price;
	private Boolean isEditting; 
	private JButton btnAdd;
	/**
	 * @wbp.parser.constructor
	 */
	public ProductForm(ProductPanel productPanel) {
		super.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		initLayout();
		this.productPanel = productPanel;
		setFrameTitle("Add Product");
		btnAdd.setText("Add");
		txtCode.setText(CodeGenerationBusiness.getProductCode());
		isEditting = false;
		
	}
	public ProductForm(ProductPanel productPanel, Long id) {
		super.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		initLayout();
		this.productID = id;
		this.productPanel = productPanel;
		isEditting = true;
		btnAdd.setText("Update");
		setFrameTitle("Edit Product");
		displayProductDetails(productID);
		
		
	}
	
	private void displayProductDetails(Long productId) {
		ProductDTO product = ManagerBusiness.getProductById(productId);
		//set data to field here
		txtCode.setText(product.getCode());
		txtName.setText(product.getName());
		cbbProductGroup.setSelectedItem(product.getGroup().getName());
		price = ManagerBusiness.findLatestPriceById(productId);
		String sellingPrice = price==null?"":price.getPrice()+"";
		txtPrice.setText(sellingPrice);
		image_filename = product.getImageFilename();
		pnlImage.setImage(FileUtil.getRelativePathFromProjectPath("/src/main/java/com/google/coffeeshop/gui/desktop/images/products/" + image_filename));
	}

	public void maximizeScreen() {
		this.setExtendedState(JFrame.MAXIMIZED_BOTH);
	}
	
	public void restoreScreen() {
		this.setExtendedState(JFrame.NORMAL);
	}
	
	public void refreshGUI() {
		this.validate();
		this.repaint();
	}
	

	private void openFileChooserDialog() {
		JFileChooser chooser = new JFileChooser(FileUtil.getRelativePathFromProjectPath("/src/main/java/com/google/coffeeshop/gui/desktop/images/products/"));
	    FileNameExtensionFilter filter = new FileNameExtensionFilter(
	        "JPG & PNG & GIF Images", "jpg", "png", "gif");
	    chooser.setFileFilter(filter);
	    int returnVal = chooser.showOpenDialog(this);
	    if(returnVal == JFileChooser.APPROVE_OPTION) {
	    	pnlImage.setImage(chooser.getSelectedFile().getAbsolutePath());
	    	image_filename = chooser.getSelectedFile().getName();
	    }
	}
	
	private void updateOrAddProduct() {
		ProductDTO modifiedProduct = getProductDTO();
		ProductDTO afterInsert =  ManagerBusiness.saveProduct(modifiedProduct);
		AddSellingPrice(afterInsert);
		refreshParentGUI();
		disposeFrame();
	}
	private void AddSellingPrice(ProductDTO product){
		try{
			long newPrice = Long.parseLong(txtPrice.getText());
			if(price==null || !isEditting || newPrice != price.getPrice()){
				ProductSellingPriceDTO sellingPrice = new ProductSellingPriceDTO();
				sellingPrice.setPrice(newPrice);
				sellingPrice.setProduct(product);
				sellingPrice.setApplyDate(new Date());
				ManagerBusiness.saveSellingPrice(sellingPrice);
			}
		}catch(Exception ex){
			
		}
	}
	private ProductDTO getProductDTO() {
		ProductDTO product = new ProductDTO();
		product.setId(productID);
		product.setCode(txtCode.getText());
		product.setName(txtName.getText());	
		product.setGroup(listProductGroup.get(cbbProductGroup.getSelectedIndex()));
		product.setInventory((long) 0);
		product.setActive(true);
		
		product.setImageFilename(image_filename);
		return product;

	}
	private void refreshParentGUI() {
		productPanel.refreshGUI();
	}
	private void disposeFrame() {
		this.dispose();
	}
	private void setFrameTitle(String title){
		lblProductTitle.setText(title);
	}
	private void initLayout(){
		setSize(600, 335);
		getContentPane().setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("max(39dlu;default)"),
				ColumnSpec.decode("max(7dlu;default)"),
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("max(121dlu;default)"),
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,},
			new RowSpec[] {
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				RowSpec.decode("default:grow"),
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				RowSpec.decode("max(31dlu;default)"),
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,}));
		
		lblProductTitle = new JLabel();
		lblProductTitle.setFont(new Font("Tahoma", Font.PLAIN, 16));
		lblProductTitle.setHorizontalAlignment(SwingConstants.CENTER);
		getContentPane().add(lblProductTitle, "2, 2, 9, 1, center, default");
		
		pnlImage = SwingFactory.createImagePanel(Boolean.TRUE);
		pnlImage.setImage(FileUtil.getRelativePathFromProjectPath("/src/main/java/com/google/coffeeshop/gui/desktop/images/products/" + SwingFactory.NO_PRODUCT_IMAGE_NAME));
		getContentPane().add(pnlImage, "2, 4, 1, 11, fill, fill");
		
		JLabel lblCode = new JLabel("Code");
		getContentPane().add(lblCode, "4, 4, right, default");
		
		txtCode = new JTextField();
		txtCode.setText(CodeGenerationBusiness.getEmployeeCode());
		getContentPane().add(txtCode, "7, 4, fill, default");
		txtCode.setColumns(10);
		
		JLabel lblName = new JLabel("Name");
		getContentPane().add(lblName, "4, 6, right, default");
		
		txtName = new JTextField();
		getContentPane().add(txtName, "7, 6, fill, default");
		txtName.setColumns(10);
		
		JLabel lblPrice = new JLabel("Price");
		getContentPane().add(lblPrice, "4, 10, right, default");
		
		cbbProductGroup = new JComboBox<>();
		getContentPane().add(cbbProductGroup, "7, 12, fill, default");
		setProductGroupModel();
		
		JLabel lblProductGroup = new JLabel("Product group");
		getContentPane().add(lblProductGroup, "4, 12, right, default");
		
		txtPrice = new ObservingTextField();
		getContentPane().add(txtPrice, "7, 10, fill, default");
		txtPrice.setColumns(10);
		
		
		JButton btnChooseImage = new JButton("Choose an image");
		btnChooseImage.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				openFileChooserDialog();
			}
		});
		getContentPane().add(btnChooseImage, "2, 16");
		
		btnAdd = new JButton("Add");
		btnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				updateOrAddProduct();
			}
		});
		getContentPane().add(btnAdd, "2, 20, 6, 1, fill, fill");
		
		JButton btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				disposeFrame();
			}
		});
		getContentPane().add(btnCancel, "10, 20, fill, fill");
	}
	private void setProductGroupModel(){
		DefaultComboBoxModel model = new DefaultComboBoxModel();
		listProductGroup = LoadingBusiness.getAllProductGroup();
		for(ProductGroupDTO group: listProductGroup){
			model.addElement(group.getName());	
		}
		
		cbbProductGroup.setModel(model);
	}
	
}
